package photosalvage.rs;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.core.Context;

import photosalvage.PhotoSalvageConstants;
import photosalvage.entity.User;

public class BaseResource {
	
	@Context
	protected ServletContext servletContext;
	
	@Context
	protected HttpServletRequest request;

	@Context
	protected HttpServletResponse response;

	public User getCurrentUser() {
		HttpSession session = request.getSession(false);
		if (session == null) {
			return null;
		}
		return (User) session.getAttribute(PhotoSalvageConstants.SESSION_KEY_USER);
	}
	
	public void saveInformations(String... infoMessages) {
		saveMessages("INFORMATIONS", infoMessages);
	}
	public void saveErrors(String... errorMessages) {
		saveMessages("ERRORS", errorMessages);
	}
	private void saveMessages(String reqKey, String... messages) {
		@SuppressWarnings("unchecked")
		List<String> msgs = (List<String>) request.getAttribute(reqKey);
		if (msgs == null) {
			msgs = new ArrayList<String>();
			request.setAttribute(reqKey, msgs);
		}
		for (String msg : messages) {
			msgs.add(msg);
		}
	}
	public boolean hasErrors() {
		@SuppressWarnings("unchecked")
		List<String> errors = (List<String>) request.getAttribute("ERRORS");
		if (errors == null) {
			return false;
		}
		return !errors.isEmpty();
	}
}
